package leetcode.problems;

/**
 * _0412 Reverse Linked List
 * 反转链表集合
 * Created by gmwang on 2018/3/23
 */
public class _0412ReverseLinkedList {
    /**
     *   Say you have an array for which the ith element is the price of a given stock on day i.
        If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
     Example 1:
         Input: [7, 1, 5, 3, 6, 4]
         Output: 5
         max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
     Example 2:
         Input: [7, 6, 4, 3, 1]
         Output: 0

         In this case, no transaction is done, i.e. max profit = 0.
         假设你有一个数组，其中i元素是给定股票在第一天的价格。
         如果你只允许最多完成一个交易（即买入一个股票，卖出一份股票），设计一个最大利润的算法。

     *
     * @param
     */
    /**
     * 思路：
     * 1. 将元素取出来，倒叙拼接成一个新的链表
     * 2. 看大神的答案用递归做的。。。
     * 
     * @param head
     * @return
     */
//    public static ListNode reverseList(ListNode head) {
//        ListNode listNode = new ListNode(0);
//        ListNode p = listNode;
//        ListNode mid = p;
//        Stack<Object> stack = new Stack<>();
//        while(head != null){
//            stack.push(head);
//            head = head.next;
//        }
//        if(stack.size() == 0) return mid.next;
//        for(int i = stack.size()-1;i >= 0;i --){
//            ListNode node = (ListNode)stack.get(i);
//            ListNode node1 = new ListNode(0);
//            node1.val = node.val;
//            p.next = node1;
//            p = p.next;
//        }
//        return mid.next;
//    }

    public ListNode reverseList(ListNode head) {
        if(head==null || head.next==null)
            return head;
        ListNode nextNode=head.next;
        ListNode newHead=reverseList(nextNode);
        nextNode.next=head;
        head.next=null;
        return newHead;
    }

    public static void main(String[] args) {
        ListNode root = new ListNode(1);
        ListNode rootL = new ListNode(2);
//        ListNode rootR = new ListNode(20);
        root.next = rootL;
//        rootL.next = rootR;
//        ListNode rootRL = new ListNode(15);
//        ListNode rootRR = new ListNode(7);
//        rootR.next = rootRL;
//        rootRL.next = rootRR;
//        ListNode listNode = reverseList(root);
//        System.out.println(listNode.val);
//        System.out.println(listNode.next.val);
//        System.out.println(listNode.next.next.val);
//        System.out.println(listNode.next.next.next.val);
    }
}
